/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.bennedum.SimpleMCClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

/**
 *
 * @author frdfsnlght <frdfsnlght@gmail.com>
 */
public final class Main {

    private static final File configFile = new File(System.getProperty("user.home") + File.separator + "simpleclient.properties");

    public static LoginWindow loginWindow = null;
    public static MainWindow mainWindow = null;
    public static Client client = null;
    public static Network network = new Network();
    public static Properties config;

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {}

        /*
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
        };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {}
        */
        
        config = new Properties();
        if (configFile.exists())
            try {
                config.load(new FileInputStream(configFile));
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, "Unable to load config!", "Error", JOptionPane.ERROR_MESSAGE);
                System.exit(1);
            }

        network.start();

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                loginWindow = new LoginWindow();
                loginWindow.setVisible(true);
            }
        });
    }

    public static void connect() {
        InetSocketAddress addr = null;
        while (addr == null) {
            String host = (String)JOptionPane.showInputDialog(null, "Server address:", "Connect", JOptionPane.PLAIN_MESSAGE, null, null, config.getProperty("server", "localhost"));
            if (host == null) System.exit(0);
            host = host.trim();
            if (host.isEmpty()) continue;
            String[] parts = host.split(":");
            String address = parts[0];
            int port = 25565;
            if (parts.length > 1)
                try {
                    port = Integer.parseInt(parts[1]);
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null, "Invalid port", "Error", JOptionPane.ERROR_MESSAGE);
                    continue;
                }
            addr = new InetSocketAddress(address, port);
            config.setProperty("server", host);
            saveConfig();
        }
        client = new Client(addr);
        client.connect();
    }

    private static DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.LONG);

    public static void out(String fmt, Object ... args) {
        System.out.format("[%s] %s\n",
                timeFormat.format(new Date()),
                String.format(fmt, args));
    }

    public static void saveConfig() {
        try {
            config.store(new FileOutputStream(configFile), "No comment");
        } catch (IOException e) {}
    }

}
